/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useEffect, useRef, useState } from 'react';
import { Button, message, Space, Popover, Spin } from 'antd';
import DragTable from '@/components/DragTable';
import ProTable from '@ant-design/pro-table';
import KbRemarksModal from '@/components/KbRemarksModal';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import type { HistoryDetailTableColumnsItem } from '@/components/_pages/ad/utils/type';
import type { Location } from 'umi';
import { getSmsPhoneDetailList, getRealPhone } from '@/services/ad/marketingSms/index';
import { ProFormText } from '@ant-design/pro-form';
import { history, useLocation } from 'umi';
import { isString } from 'lodash';
import styles from './index.less';

const Index = () => {
  const location = useLocation() as Location;
  const actionRef = useRef<ActionType>();
  const [plaintext, setPlaintext] = useState<string[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [record, setRecord] = useState<any>({});
  const [recordItem, setRecordItem] = useState<any>({});
  const [showPopover, setShowPopover] = useState<string>('');
  const [visible, setVisible] = useState<boolean>(false);
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const queryTable = async (values: any) => {
    const { current: page, pageSize } = values;
    const { code, data, msg } = await getSmsPhoneDetailList({ page, pageSize, id: record.id });
    if (code == 0) {
      return {
        data: data.list,
        total: data.total,
      };
    } else {
      message.error(msg);
      return {};
    }
  };
  const handleVisibleChange = (newVisible: boolean, id: string) => {
    if (newVisible) {
      setLoading(true);
      getRealPhone({ id }).then((res) => {
        setLoading(false);
        const { code, msg } = res;
        if (code == 0) {
          setShowPopover(id);
          if (id == showPopover) {
            setVisible(false);
          }
          setPlaintext([...plaintext, id]);
        } else {
          message.error(msg);
        }
      });
    } else {
      setShowPopover('');
      setVisible(false);
    }
  };
  const handleRemark = (recordItem_: any) => {
    setRecordItem(recordItem_);
    setModalVisible(true);
  };

  /**
   * 隐藏主要字段
   */
  const importFieldHide = (str: string, start = 0, end = str.length, replaceBy = '*') => {
    if (!str || !isString(str)) {
      return str;
    }

    let text = '';
    const replaceTextLength = str.slice(start, end).length;
    while (text.length < replaceTextLength) {
      text += replaceBy;
    }

    return `${str.slice(0, start)}${text}${str.slice(end)}`;
  };

  const detailColumns: ProColumns<HistoryDetailTableColumnsItem>[] = [
    {
      title: '序号',
      dataIndex: 'id',
      search: false,
      align: 'center',
      ellipsis: true,
    },
    {
      title: '账号',
      dataIndex: 'phone',
      search: false,
      align: 'center',
      ellipsis: true,
      render: (_, record_) => {
        return importFieldHide(record_.phone, 4, 7);
      },
    },
    {
      title: '操作',
      align: 'center',
      valueType: 'option',
      render: (_, record_) => {
        const { id, is_look, phone } = record_;
        return (
          <Space>
            <a
              style={{
                color: `${is_look == '1' || plaintext.includes(id) ? '#73cc73' : '#3597fd'}`,
              }}
            >
              <Popover
                key={id}
                content={phone}
                trigger='click'
                open={showPopover == id || visible}
                onOpenChange={(newVisible) => handleVisibleChange(newVisible, id)}
              >
                查看明文
              </Popover>
            </a>
            <a onClick={handleRemark.bind(null, record_)}>备注</a>
          </Space>
        );
      },
    },
  ];

  const goBackMarketingSms = () => history.goBack();
  useEffect(() => {
    setRecord(location.query);
  }, [location.key]);
  return (
    <DragTable>
      <Spin spinning={loading} size='large'>
        <ProTable<HistoryDetailTableColumnsItem>
          rowKey='id'
          className={styles.detailTable}
          actionRef={actionRef}
          toolBarRender={false}
          columns={detailColumns}
          request={queryTable}
          search={{
            span: 24,
            optionRender: () => [
              <Space direction='vertical' key='text'>
                <ProFormText label='短信主题：' readonly fieldProps={{ value: record.task_name }} />
                <ProFormText
                  label='短信内容：'
                  readonly
                  fieldProps={{ value: record.sms_content }}
                />
              </Space>,
              <Button type='primary' onClick={goBackMarketingSms} key='option'>
                返回短信列表
              </Button>,
            ],
          }}
          style={{ padding: 24 }}
        />
      </Spin>
      <KbRemarksModal
        modalTitle={`添加备注 ｜ ${importFieldHide(recordItem.phone, 4, 7)}`}
        required
        visible={modalVisible}
        setVisible={setModalVisible}
        formatDataMap={{
          label: 'operator_name',
          remark: 'content',
          user: 'operator_phone',
          time: 'created_at',
        }}
        api='/order/addPhoneRemark'
        formData={{ id: recordItem.id }}
        listApi='/order/getPhoneRemarkList'
        listFormData={{ id: recordItem.id }}
      ></KbRemarksModal>
    </DragTable>
  );
};

export default Index;
